package chatsystem;

import chatsystem.gui.ChatGUI;
import chatsystem.ni.ChatNI;
import java.io.*;

/** Synchronise le GUI avec le NI. */
public class Presenter implements chatsystem.ni.FromNI,
                                  chatsystem.gui.FromGUI
{
   private ChatGUI gui;
   private ChatNI ni; // n'existe que lorsqu'on est connecté.
   
   public void setGUI(ChatGUI g) {gui = g;} 

/* From NI ********************************************************************/
   
   
   public void onNewPeer(String nickname) {
      gui.addPeer(nickname);
   }

   public void onMessage(String peer, String message) {
      gui.showMessage(peer, message);
   }

   public void onFileRequest(String peer, String filename) {
      gui.fileRecv(peer, filename);
   }
   
   public void onPeerDisconnect(String nickname) {
      gui.removePeer(nickname);
   }

/* From GUI *******************************************************************/
   
   public void onConnect(String nickname) {
      try {
         ni = new ChatNI(this, "255.255.255.255", 16050);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }
      gui.showConnected(true);
      ni.sendHello(nickname);
   }

   public void sendMessage(String peer, String message) {
      ni.sendMessage(peer, message);
   }

   public void sendFile(String path, String peer, FileTransferStatusCB cb)
   {
      try {
         File f = new File(path);
         InputStream file = new FileInputStream(path);
         ni.startFileTransfer(file, f.getName(), peer, cb);
      } catch (IOException e) {
         cb.onError("Can't open file");
      }
   }
   
   public void acceptFile(boolean accept, FileTransferStatusCB cb)
   {
      ni.acceptFileTransfer(accept, cb);
   }
   
   public void abortFileSend()   {ni.abortFileSend();}
   public void abortFileRecv()   {ni.abortFileRecv();}
   
   public void onDisconnect() 
   {
      if (ni != null) {
         ni.sendGoodbye();
         ni.stop();
         ni = null;
         gui.showConnected(false);
      }
   }
  
}
